import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:travel/model/tourism.dart';
import 'package:travel/routes/index.dart';
import 'package:travel/screen/flutter_screenutil.dart';

import 'dart:math' as math;

import 'package:travel/utils/colors.dart';
import 'package:travel/utils/radian.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

class IndexController extends GetxController {
  RxList<String> attractions =
      RxList(['北京', '故宫', '天安门', '温泉', '世界杯', '景山公园', '天坛', '鸟巢', '长城', '王府井']);

  ScrollController scrollController = ScrollController();

  RxString city = '北京市'.obs;

  RxBool isLoading = false.obs;

  RxBool hasNext = true.obs;

  RxInt total = 20.obs;

  RxList<TourismModel> data = RxList([]);

  Future<void> onRefresh() {
    return Future.delayed(const Duration(seconds: 1), () {
      data.clear();
      initData();
    });
  }

  @override
  void onInit() {
    super.onInit();
    initData();
    scrollController.addListener(() {
      if (isLoading.isFalse &&
          scrollController.position.pixels >= scrollController.position.maxScrollExtent) {
        isLoading.value = true;
        loadMoreData();
      }
    });
  }

  void initData() {
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p0.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 1.1,
        nickname: '晚风心里吹'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p7.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p8.png',
        browse: 1.3,
        nickname: '唐糖唐来了'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p2.png',
        describe: '北京海拔2000米的木栈道帝都最高观景平台',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p3.png',
        browse: 2.1,
        nickname: '美腻的猫'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p9.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '小沈阳10'));

    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p4.png',
        describe: '北京郊区大自然山景私汤山酒店',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p5.png',
        browse: 1.1,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p11.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p12.png',
        browse: 1.7,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p6.png',
        describe: '北京周末去哪，找到了人少景美的仙境了！',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 3.1,
        nickname: '晚风吹心里'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p13.png',
        describe: '秋冬京城小奈良动物园里泡温泉',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '万能夏小姐'));
  }

  Future<void> loadMoreData() {
    return Future.delayed(const Duration(seconds: 1), () {
      if (total.value > data.length) {
        hasNext.value = true;
        isLoading.value = false;
        initData();
        return;
      }
      hasNext.value = false;
      isLoading.value = false;
    });
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }
}

class IndexPage extends GetView<IndexController> {
  const IndexPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<IndexController>(
      builder: (_) {
        return Obx(() => Scaffold(
              backgroundColor: ColorsUtils.backgroundColor,
              appBar: AppBar(
                automaticallyImplyLeading: false,
                title: Container(
                  height: 35.h,
                  decoration: BoxDecoration(
                      color: const Color.fromRGBO(255, 255, 255, 0.898039215686275),
                      borderRadius: BorderRadius.circular(17.5.r)),
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 3.w),
                  margin: EdgeInsets.symmetric(horizontal: 10.w),
                  child: Row(
                    children: [
                      Expanded(
                          child: TextField(
                        decoration: InputDecoration(
                            prefixIcon: Icon(Icons.search_sharp, size: 25.sp),
                            prefixIconColor: Colors.black54,
                            prefixIconConstraints: BoxConstraints.expand(width: 35.w),
                            border: InputBorder.none,
                            focusedBorder: InputBorder.none,
                            hintText: '搜索目的地/景点',
                            contentPadding: EdgeInsets.symmetric(vertical: 13.h),
                            isCollapsed: true,
                            isDense: true,
                            hintStyle: TextStyle(
                                color: const Color.fromRGBO(102, 102, 102, 1),
                                fontWeight: FontWeight.normal,
                                fontSize: 13.sp,
                                fontFamily: 'YaHei')),
                        readOnly: true,
                        onTap: () {
                          Get.toNamed(RoutePath.search);
                        },
                      )),
                      InkWell(
                        onTap: () {
                          Get.toNamed(RoutePath.search);
                        },
                        child: Container(
                          constraints: BoxConstraints.expand(width: 58.w, height: 31.h),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(16.5.r),
                              gradient: const LinearGradient(
                                  colors: [
                                    Color.fromRGBO(52, 120, 246, 1),
                                    Color.fromRGBO(2, 167, 240, 1)
                                  ],
                                  transform: GradientRotation(math.pi),
                                  stops: [0.0, 0.99])),
                          child: Text(
                            '搜索',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 13.sp,
                                fontWeight: FontWeight.normal,
                                fontFamily: 'YaHei'),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                flexibleSpace: Container(
                  decoration: const BoxDecoration(
                      gradient: LinearGradient(
                          colors: [Color.fromRGBO(52, 120, 246, 1), Color.fromRGBO(2, 167, 240, 1)],
                          stops: [0.0, 0.99],
                          transform: GradientRotation(math.pi / 2))),
                ),
                elevation: 0,
                bottom: bottom,
                systemOverlayStyle: SystemUiOverlayStyle.light,
              ),
              body: refreshIndicator,
            ));
      },
      init: Get.put(IndexController()),
    );
  }

  RefreshIndicator get refreshIndicator {
    return RefreshIndicator(
      onRefresh: controller.onRefresh,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(10).w,
        controller: controller.scrollController,
        child: Column(
          children: [
            StaggeredGrid.count(
              crossAxisCount: 4,
              crossAxisSpacing: 3.w,
              mainAxisSpacing: 3.h,
              children: [
                InkWell(
                    onTap: () {
                      Get.toNamed(RoutePath.theme, arguments: {'theme': '亲子游'});
                    },
                    child: Container(
                      height: 69.h,
                      width: 87.w,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                            ColorsUtils.rgba(5, 178, 136, 1),
                            ColorsUtils.rgba(49, 162, 149, 1)
                          ], stops: const [
                            0.1,
                            1.0
                          ], transform: GradientRotation(RadianUtils.angleToRadian(14))),
                          borderRadius: BorderRadius.only(topLeft: const Radius.circular(8).w)),
                      child: Column(
                        children: [
                          Expanded(
                              flex: 5,
                              child: Center(
                                child:
                                    ToolsUtils.assetImageSvg('u189.svg', width: 23.w, height: 22.h),
                              )),
                          Expanded(
                              flex: 3,
                              child: Align(
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '亲子游',
                                  style: StylesUtils.customTextStyle(fontSize: 12.sp),
                                ),
                              ))
                        ],
                      ),
                    )),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.theme, arguments: {'theme': '文化游'});
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [
                      ColorsUtils.rgba(49, 116, 246, 1),
                      ColorsUtils.rgba(106, 172, 248, 1)
                    ], stops: const [
                      0.0,
                      1.0
                    ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u195.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '文化游',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.theme, arguments: {'theme': '温泉游'});
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        //linear-gradient(0deg, rgba(254, 111, 73, 1) 0%, rgba(234, 52, 45, 1) 100%)
                        gradient: LinearGradient(colors: [
                      ColorsUtils.rgba(254, 111, 73, 1),
                      ColorsUtils.rgba(234, 52, 45, 1)
                    ], stops: const [
                      0.0,
                      1.0
                    ], transform: const GradientRotation(0))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u231.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '温泉游',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.theme, arguments: {'theme': '周边游'});
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(topRight: const Radius.circular(8).w),
                        gradient: LinearGradient(colors: [
                          ColorsUtils.rgba(65, 94, 244, 1),
                          ColorsUtils.rgba(115, 160, 255, 1)
                        ], stops: const [
                          0.0,
                          1.0
                        ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u192.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '周边游',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.map);
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(bottomLeft: const Radius.circular(8).w),
                        gradient: LinearGradient(colors: [
                          ColorsUtils.rgba(119, 132, 245, 1),
                          ColorsUtils.rgba(125, 125, 232, 1)
                        ], stops: const [
                          0.0,
                          1.0
                        ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u179.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '旅游地图',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.hotel);
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [
                      ColorsUtils.rgba(210, 63, 63, 1),
                      ColorsUtils.rgba(246, 135, 91, 1)
                    ], stops: const [
                      0.0,
                      1.0
                    ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u198.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '酒店民宿',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                Stack(
                  children: [
                    Container(
                      height: 69.h,
                      width: 87.w,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                        ColorsUtils.rgba(102, 132, 255, 1),
                        ColorsUtils.rgba(113, 159, 255, 1)
                      ], stops: const [
                        0.0,
                        1.0
                      ], transform: const GradientRotation(math.pi))),
                      child: Column(
                        children: [
                          Expanded(
                              flex: 5,
                              child: Center(
                                child:
                                    ToolsUtils.assetImageSvg('u225.svg', width: 23.w, height: 22.h),
                              )),
                          Expanded(
                              flex: 3,
                              child: Align(
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '汽车票',
                                  style: StylesUtils.customTextStyle(fontSize: 12.sp),
                                ),
                              ))
                        ],
                      ),
                    ),
                    Positioned(
                        top: 0,
                        left: 0,
                        width: 32,
                        height: 32,
                        child: CustomPaint(
                            painter: _MyCustomPaint(),
                            child: Transform.rotate(
                              angle: RadianUtils.angleToRadian(318),
                              child: Container(
                                padding: const EdgeInsets.only(top: 5),
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '规划中',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 8.sp,
                                      color: ColorsUtils.color3333,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                            ))),
                  ],
                ),
                Stack(
                  children: [
                    Container(
                      height: 69.h,
                      width: 87.w,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(bottomRight: const Radius.circular(8).w),
                          gradient: LinearGradient(colors: [
                            ColorsUtils.rgba(255, 171, 37, 1),
                            ColorsUtils.rgba(255, 115, 61, 1)
                          ], stops: const [
                            0.0,
                            1.0
                          ], transform: const GradientRotation(math.pi))),
                      child: Column(
                        children: [
                          Expanded(
                              flex: 5,
                              child: Center(
                                child:
                                    ToolsUtils.assetImageSvg('u219.svg', width: 23.w, height: 22.h),
                              )),
                          Expanded(
                              flex: 3,
                              child: Align(
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '飞机票',
                                  style: StylesUtils.customTextStyle(fontSize: 12.sp),
                                ),
                              ))
                        ],
                      ),
                    ),
                    Positioned(
                        top: 0,
                        left: 0,
                        width: 32,
                        height: 32,
                        child: CustomPaint(
                            painter: _MyCustomPaint(),
                            child: Transform.rotate(
                              angle: RadianUtils.angleToRadian(318),
                              child: Container(
                                padding: const EdgeInsets.only(top: 5),
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '规划中',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 8.sp,
                                      color: ColorsUtils.color3333,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                            ))),
                  ],
                )
              ],
            ),
            InkWell(
              onTap: () {
                Get.toNamed(RoutePath.theme, arguments: {'theme': '主题旅游'});
              },
              child: Container(
                height: 120.h,
                margin: EdgeInsets.symmetric(vertical: 10.h),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.w),
                    image: DecorationImage(
                        image: ToolsUtils.assetImage('index.png'), fit: BoxFit.fill)),
              ),
            ),
            Container(
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.only(bottom: 10.h),
                child: InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.city);
                  },
                  child: Wrap(
                    runAlignment: WrapAlignment.center,
                    crossAxisAlignment: WrapCrossAlignment.center,
                    spacing: 5.w,
                    children: [
                      Icon(Icons.location_on_outlined,
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3478),
                          size: 15.w),
                      Text(
                        '带你玩遍',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                      ),
                      Text.rich(TextSpan(children: [
                        TextSpan(
                          text: controller.city.value,
                          style: StylesUtils.customTextStyle(color: ColorsUtils.color3478),
                        ),
                        WidgetSpan(
                            alignment: PlaceholderAlignment.middle,
                            child: Icon(
                              Icons.arrow_right,
                              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                              size: 15.w,
                            ))
                      ]))
                    ],
                  ),
                )),
            StaggeredGrid.count(
              crossAxisCount: 2,
              crossAxisSpacing: 10.w,
              mainAxisSpacing: 5.h,
              children: controller.data
                  .map((e) => Container(
                        // height: 256.h,
                        margin: EdgeInsets.only(bottom: 10.w),
                        decoration: BoxDecoration(
                            color: Colors.white, borderRadius: BorderRadius.circular(8.w)),
                        child: Column(
                          children: [
                            Container(
                              height: 130.h,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(8.w),
                                      topRight: Radius.circular(8.w)),
                                  image: DecorationImage(
                                      alignment: Alignment.topLeft,
                                      fit: BoxFit.fill,
                                      filterQuality: FilterQuality.high,
                                      image: NetworkImage(
                                        e.imgUrl,
                                      ))),
                            ),
                            Container(
                              margin: EdgeInsets.symmetric(vertical: 8.w),
                              alignment: Alignment.centerLeft,
                              child: Text(
                                e.describe,
                                overflow: TextOverflow.ellipsis,
                                maxLines: 2,
                                style: StylesUtils.customTextStyle(
                                  fontWeight: FontWeight.w700,
                                  color: ColorsUtils.color3333,
                                ),
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                    child: Text.rich(
                                  TextSpan(children: [
                                    WidgetSpan(
                                        child: CircleAvatar(
                                      radius: 10,
                                      backgroundImage: NetworkImage(e.avatar),
                                    )),
                                    TextSpan(
                                        text: '  ${e.nickname}',
                                        style: StylesUtils.customTextStyle(
                                            color: ColorsUtils.color6666, fontSize: 13.sp))
                                  ]),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                )),
                                Text.rich(TextSpan(children: [
                                  WidgetSpan(
                                      child: Icon(Icons.remove_red_eye_outlined,
                                          color: ColorsUtils.parseColorFromHexString(
                                              ColorsUtils.color3333),
                                          size: 15.w),
                                      alignment: PlaceholderAlignment.middle),
                                  TextSpan(
                                      text: '${e.browse}万',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color6666, fontSize: 13.sp))
                                ]))
                              ],
                            )
                          ],
                        ),
                      ))
                  .toList(),
            ),
            if (controller.hasNext.isFalse)
              renderBottom()
            else if (controller.isLoading.isTrue)
              renderBottom()
          ],
        ),
      ),
    );
  }

  PreferredSize get bottom {
    return PreferredSize(
        preferredSize: Size.fromHeight(35.h),
        child: SizedBox(
          height: 35.h,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10, top: 0),
            itemBuilder: (BuildContext context, int index) {
              return InkWell(
                onTap: () {
                  Get.toNamed(RoutePath.searchResult);
                },
                child: Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  constraints: const BoxConstraints(maxHeight: 25),
                  decoration: BoxDecoration(
                      color: const Color.fromRGBO(255, 255, 255, 0.2),
                      borderRadius: BorderRadius.circular(12.5)),
                  child: Text(controller.attractions[index],
                      style: TextStyle(
                          fontFamily: 'YaHei',
                          fontSize: 12.sp,
                          fontWeight: FontWeight.normal,
                          color: Colors.white)),
                ),
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              return VerticalDivider(
                width: 10.w,
                indent: 0,
                endIndent: 0,
                color: Colors.transparent,
              );
            },
            itemCount: controller.attractions.length,
          ),
        ));
  }

  Widget renderBottom() {
    if (controller.hasNext.isFalse) {
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        alignment: Alignment.center,
        child: const Text(
          '已经到底',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF333333),
          ),
        ),
      );
    }
    if (controller.isLoading.isTrue) {
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      );
    }
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    );
  }
}

class _MyCustomPaint extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = ColorsUtils.parseColorFromHexString('#FECF54')
      ..isAntiAlias = true
      ..style = PaintingStyle.fill;
    Path path = Path();
    path.moveTo(0, 12);
    path.lineTo(0, size.height);
    path.lineTo(size.width, 0);
    path.lineTo(12, 0);
    path.close();
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}

class IndexView extends StatefulWidget {
  const IndexView({super.key});

  @override
  State<IndexView> createState() => _IndexViewState();
}

class _IndexViewState extends State<IndexView> {
  List<String> attractions = ['北京', '故宫', '天安门', '温泉', '世界杯', '景山公园', '天坛', '鸟巢', '长城', '王府井'];

  ScrollController scrollController = ScrollController();

  String city = '北京市';

  bool isLoading = false;

  bool hasNext = true;

  int total = 20;

  List<TourismModel> data = [];

  Future<void> onRefresh() {
    return Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        data.clear();
        initData();
      });
    });
  }

  void initData() {
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p0.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 1.1,
        nickname: '晚风心里吹'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p7.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p8.png',
        browse: 1.3,
        nickname: '唐糖唐来了'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p2.png',
        describe: '北京海拔2000米的木栈道帝都最高观景平台',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p3.png',
        browse: 2.1,
        nickname: '美腻的猫'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p9.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '小沈阳10'));

    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p4.png',
        describe: '北京郊区大自然山景私汤山酒店',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p5.png',
        browse: 1.1,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p11.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p12.png',
        browse: 1.7,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p6.png',
        describe: '北京周末去哪，找到了人少景美的仙境了！',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 3.1,
        nickname: '晚风吹心里'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p13.png',
        describe: '秋冬京城小奈良动物园里泡温泉',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '万能夏小姐'));
  }

  Future<void> loadMoreData() {
    return Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        if (total > data.length) {
          hasNext = true;
          isLoading = false;
          initData();
          return;
        }
        hasNext = false;
        isLoading = false;
      });
    });
  }

  @override
  void initState() {
    initData();
    scrollController.addListener(() {
      if (isLoading == false &&
          scrollController.position.pixels >= scrollController.position.maxScrollExtent) {
        setState(() {
          isLoading = true;
        });
        loadMoreData();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorsUtils.backgroundColor,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Container(
          height: 35.h,
          decoration: BoxDecoration(
              color: const Color.fromRGBO(255, 255, 255, 0.898039215686275),
              borderRadius: BorderRadius.circular(17.5.r)),
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.symmetric(horizontal: 3.w),
          margin: EdgeInsets.symmetric(horizontal: 10.w),
          child: Row(
            children: [
              Expanded(
                  child: TextField(
                decoration: InputDecoration(
                    prefixIcon: Icon(Icons.search_sharp, size: 25.sp),
                    prefixIconColor: Colors.black54,
                    prefixIconConstraints: BoxConstraints.expand(width: 35.w),
                    border: InputBorder.none,
                    focusedBorder: InputBorder.none,
                    hintText: '搜索目的地/景点',
                    contentPadding: EdgeInsets.symmetric(vertical: 13.h),
                    isCollapsed: true,
                    isDense: true,
                    hintStyle: TextStyle(
                        color: const Color.fromRGBO(102, 102, 102, 1),
                        fontWeight: FontWeight.normal,
                        fontSize: 13.sp,
                        fontFamily: 'YaHei')),
                readOnly: true,
                onTap: () {
                  Get.toNamed(RoutePath.search);
                },
              )),
              InkWell(
                onTap: () {
                  Get.toNamed(RoutePath.search);
                },
                child: Container(
                  constraints: BoxConstraints.expand(width: 58.w, height: 31.h),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(16.5.r),
                      gradient: const LinearGradient(
                          colors: [Color.fromRGBO(52, 120, 246, 1), Color.fromRGBO(2, 167, 240, 1)],
                          transform: GradientRotation(math.pi),
                          stops: [0.0, 0.99])),
                  child: Text(
                    '搜索',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 13.sp,
                        fontWeight: FontWeight.normal,
                        fontFamily: 'YaHei'),
                  ),
                ),
              )
            ],
          ),
        ),
        flexibleSpace: Container(
          decoration: const BoxDecoration(
              gradient: LinearGradient(
                  colors: [Color.fromRGBO(52, 120, 246, 1), Color.fromRGBO(2, 167, 240, 1)],
                  stops: [0.0, 0.99],
                  transform: GradientRotation(math.pi / 2))),
        ),
        elevation: 0,
        bottom: bottom,
        systemOverlayStyle: SystemUiOverlayStyle.light,
      ),
      body: refreshIndicator,
    );
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  RefreshIndicator get refreshIndicator {
    return RefreshIndicator(
      onRefresh: onRefresh,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(10).w,
        controller: scrollController,
        child: Column(
          children: [
            StaggeredGrid.count(
              crossAxisCount: 4,
              crossAxisSpacing: 3.w,
              mainAxisSpacing: 3.h,
              children: [
                InkWell(
                    onTap: () {
                      Get.toNamed(RoutePath.theme, arguments: {'theme': '亲子游'});
                    },
                    child: Container(
                      height: 69.h,
                      width: 87.w,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                            ColorsUtils.rgba(5, 178, 136, 1),
                            ColorsUtils.rgba(49, 162, 149, 1)
                          ], stops: const [
                            0.1,
                            1.0
                          ], transform: GradientRotation(RadianUtils.angleToRadian(14))),
                          borderRadius: BorderRadius.only(topLeft: const Radius.circular(8).w)),
                      child: Column(
                        children: [
                          Expanded(
                              flex: 5,
                              child: Center(
                                child:
                                    ToolsUtils.assetImageSvg('u189.svg', width: 23.w, height: 22.h),
                              )),
                          Expanded(
                              flex: 3,
                              child: Align(
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '亲子游',
                                  style: StylesUtils.customTextStyle(fontSize: 12.sp),
                                ),
                              ))
                        ],
                      ),
                    )),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.theme, arguments: {'theme': '文化游'});
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [
                      ColorsUtils.rgba(49, 116, 246, 1),
                      ColorsUtils.rgba(106, 172, 248, 1)
                    ], stops: const [
                      0.0,
                      1.0
                    ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u195.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '文化游',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.theme, arguments: {'theme': '温泉游'});
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        //linear-gradient(0deg, rgba(254, 111, 73, 1) 0%, rgba(234, 52, 45, 1) 100%)
                        gradient: LinearGradient(colors: [
                      ColorsUtils.rgba(254, 111, 73, 1),
                      ColorsUtils.rgba(234, 52, 45, 1)
                    ], stops: const [
                      0.0,
                      1.0
                    ], transform: const GradientRotation(0))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u231.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '温泉游',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.theme, arguments: {'theme': '周边游'});
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(topRight: const Radius.circular(8).w),
                        gradient: LinearGradient(colors: [
                          ColorsUtils.rgba(65, 94, 244, 1),
                          ColorsUtils.rgba(115, 160, 255, 1)
                        ], stops: const [
                          0.0,
                          1.0
                        ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u192.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '周边游',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.map);
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(bottomLeft: const Radius.circular(8).w),
                        gradient: LinearGradient(colors: [
                          ColorsUtils.rgba(119, 132, 245, 1),
                          ColorsUtils.rgba(125, 125, 232, 1)
                        ], stops: const [
                          0.0,
                          1.0
                        ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u179.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '旅游地图',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.hotel);
                  },
                  child: Container(
                    height: 69.h,
                    width: 87.w,
                    decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [
                      ColorsUtils.rgba(210, 63, 63, 1),
                      ColorsUtils.rgba(246, 135, 91, 1)
                    ], stops: const [
                      0.0,
                      1.0
                    ], transform: const GradientRotation(math.pi))),
                    child: Column(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Center(
                              child:
                                  ToolsUtils.assetImageSvg('u198.svg', width: 23.w, height: 22.h),
                            )),
                        Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.topCenter,
                              child: Text(
                                '酒店民宿',
                                style: StylesUtils.customTextStyle(fontSize: 12.sp),
                              ),
                            ))
                      ],
                    ),
                  ),
                ),
                Stack(
                  children: [
                    Container(
                      height: 69.h,
                      width: 87.w,
                      decoration: BoxDecoration(
                          gradient: LinearGradient(colors: [
                        ColorsUtils.rgba(102, 132, 255, 1),
                        ColorsUtils.rgba(113, 159, 255, 1)
                      ], stops: const [
                        0.0,
                        1.0
                      ], transform: const GradientRotation(math.pi))),
                      child: Column(
                        children: [
                          Expanded(
                              flex: 5,
                              child: Center(
                                child:
                                    ToolsUtils.assetImageSvg('u225.svg', width: 23.w, height: 22.h),
                              )),
                          Expanded(
                              flex: 3,
                              child: Align(
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '汽车票',
                                  style: StylesUtils.customTextStyle(fontSize: 12.sp),
                                ),
                              ))
                        ],
                      ),
                    ),
                    Positioned(
                        top: 0,
                        left: 0,
                        width: 32,
                        height: 32,
                        child: CustomPaint(
                            painter: _MyCustomPaint(),
                            child: Transform.rotate(
                              angle: RadianUtils.angleToRadian(318),
                              child: Container(
                                padding: const EdgeInsets.only(top: 5),
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '规划中',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 8.sp,
                                      color: ColorsUtils.color3333,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                            ))),
                  ],
                ),
                Stack(
                  children: [
                    Container(
                      height: 69.h,
                      width: 87.w,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(bottomRight: const Radius.circular(8).w),
                          gradient: LinearGradient(colors: [
                            ColorsUtils.rgba(255, 171, 37, 1),
                            ColorsUtils.rgba(255, 115, 61, 1)
                          ], stops: const [
                            0.0,
                            1.0
                          ], transform: const GradientRotation(math.pi))),
                      child: Column(
                        children: [
                          Expanded(
                              flex: 5,
                              child: Center(
                                child:
                                    ToolsUtils.assetImageSvg('u219.svg', width: 23.w, height: 22.h),
                              )),
                          Expanded(
                              flex: 3,
                              child: Align(
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '飞机票',
                                  style: StylesUtils.customTextStyle(fontSize: 12.sp),
                                ),
                              ))
                        ],
                      ),
                    ),
                    Positioned(
                        top: 0,
                        left: 0,
                        width: 32,
                        height: 32,
                        child: CustomPaint(
                            painter: _MyCustomPaint(),
                            child: Transform.rotate(
                              angle: RadianUtils.angleToRadian(318),
                              child: Container(
                                padding: const EdgeInsets.only(top: 5),
                                alignment: Alignment.topCenter,
                                child: Text(
                                  '规划中',
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 8.sp,
                                      color: ColorsUtils.color3333,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                            ))),
                  ],
                )
              ],
            ),
            InkWell(
              onTap: () {
                Get.toNamed(RoutePath.theme, arguments: {'theme': '主题旅游'});
              },
              child: Container(
                height: 120.h,
                margin: EdgeInsets.symmetric(vertical: 10.h),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10.w),
                    image: DecorationImage(
                        image: ToolsUtils.assetImage('index.png'), fit: BoxFit.fill)),
              ),
            ),
            Container(
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.only(bottom: 10.h),
                child: InkWell(
                  onTap: () {
                    Get.toNamed(RoutePath.city);
                  },
                  child: Wrap(
                    runAlignment: WrapAlignment.center,
                    crossAxisAlignment: WrapCrossAlignment.center,
                    spacing: 5.w,
                    children: [
                      Icon(Icons.location_on_outlined,
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3478),
                          size: 15.w),
                      Text(
                        '带你玩遍',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                      ),
                      Text.rich(TextSpan(children: [
                        TextSpan(
                          text: city,
                          style: StylesUtils.customTextStyle(color: ColorsUtils.color3478),
                        ),
                        WidgetSpan(
                            alignment: PlaceholderAlignment.middle,
                            child: Icon(
                              Icons.arrow_right,
                              color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                              size: 15.w,
                            ))
                      ]))
                    ],
                  ),
                )),
            StaggeredGrid.count(
              crossAxisCount: 2,
              crossAxisSpacing: 10.w,
              mainAxisSpacing: 5.h,
              children: data
                  .map((e) => InkWell(
                        onTap: () {
                          Get.toNamed(RoutePath.attractionsArticle, arguments: {'model': e});
                        },
                        child: Container(
                          // height: 256.h,
                          margin: EdgeInsets.only(bottom: 10.w),
                          decoration: BoxDecoration(
                              color: Colors.white, borderRadius: BorderRadius.circular(8.w)),
                          child: Column(
                            children: [
                              Container(
                                height: 130.h,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.only(
                                        topLeft: Radius.circular(8.w),
                                        topRight: Radius.circular(8.w)),
                                    image: DecorationImage(
                                        alignment: Alignment.topLeft,
                                        fit: BoxFit.fill,
                                        filterQuality: FilterQuality.high,
                                        image: NetworkImage(
                                          e.imgUrl,
                                        ))),
                              ),
                              Container(
                                margin: EdgeInsets.symmetric(vertical: 8.w),
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  e.describe,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                  style: StylesUtils.customTextStyle(
                                    fontWeight: FontWeight.w700,
                                    color: ColorsUtils.color3333,
                                  ),
                                ),
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Expanded(
                                      child: Text.rich(
                                    TextSpan(children: [
                                      WidgetSpan(
                                          child: CircleAvatar(
                                        radius: 10,
                                        backgroundImage: NetworkImage(e.avatar),
                                      )),
                                      TextSpan(
                                          text: '  ${e.nickname}',
                                          style: StylesUtils.customTextStyle(
                                              color: ColorsUtils.color6666, fontSize: 13.sp))
                                    ]),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  )),
                                  Text.rich(TextSpan(children: [
                                    WidgetSpan(
                                        child: Icon(Icons.remove_red_eye_outlined,
                                            color: ColorsUtils.parseColorFromHexString(
                                                ColorsUtils.color3333),
                                            size: 15.w),
                                        alignment: PlaceholderAlignment.middle),
                                    TextSpan(
                                        text: '${e.browse}万',
                                        style: StylesUtils.customTextStyle(
                                            color: ColorsUtils.color6666, fontSize: 13.sp))
                                  ]))
                                ],
                              )
                            ],
                          ),
                        ),
                      ))
                  .toList(),
            ),
            if (hasNext == false) renderBottom() else if (isLoading == true) renderBottom()
          ],
        ),
      ),
    );
  }

  PreferredSize get bottom {
    return PreferredSize(
        preferredSize: Size.fromHeight(35.h),
        child: SizedBox(
          height: 35.h,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10, top: 0),
            itemBuilder: (BuildContext context, int index) {
              return InkWell(
                onTap: () {
                  Get.toNamed(RoutePath.searchResult);
                },
                child: Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  constraints: const BoxConstraints(maxHeight: 25),
                  decoration: BoxDecoration(
                      color: const Color.fromRGBO(255, 255, 255, 0.2),
                      borderRadius: BorderRadius.circular(12.5)),
                  child: Text(attractions[index],
                      style: TextStyle(
                          fontFamily: 'YaHei',
                          fontSize: 12.sp,
                          fontWeight: FontWeight.normal,
                          color: Colors.white)),
                ),
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              return VerticalDivider(
                width: 10.w,
                indent: 0,
                endIndent: 0,
                color: Colors.transparent,
              );
            },
            itemCount: attractions.length,
          ),
        ));
  }

  Widget renderBottom() {
    if (hasNext == false) {
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        alignment: Alignment.center,
        child: const Text(
          '已经到底',
          style: TextStyle(
            fontSize: 15,
            color: Color(0xFF333333),
          ),
        ),
      );
    }
    if (isLoading == true) {
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      );
    }
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    );
  }
}
